package com.aabte.feignhttp.feignfastjson;

import com.alibaba.fastjson.JSON;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;

/**
 * @author Daniel
 */
public class FastJsonDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (response.body() == null) {
            return null;
        }
        Reader reader = response.body().asReader();
        if (!reader.markSupported()) {
            reader = new BufferedReader(reader, 1);
        }
        // Read the first byte to see if we have any data
        reader.mark(1);
        if (reader.read() == -1) {
            // Eagerly returning null avoids "No content to map due to end-of-input"
            return null;
        }
        reader.reset();
        StringBuilder sb = new StringBuilder();
        char[] buff = new char[4096];
        for (int n; (n = reader.read(buff)) != -1; ) {
            sb.append(buff, 0, n);
        }
        return JSON.parseObject(sb.toString(), type);
    }
}
